<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               v-model:page="page"
               v-model:search="search"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @sort-change="sortChange"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange"
               :summary-method="summaryMethod">
      <template #menu-left>
        <el-button
                type="warning"
                icon="el-icon-download"
                @click="handleExport"
        >导出
        </el-button>
      </template>
      <!--<template #deptName-search>-->
        <!--<el-input v-model="search.deptName"  placeholder="请输入所属机构11"/>-->
      <!--</template>-->
    </avue-crud>
  </basic-container>
</template>

<script>
  import {getList, getDetail, add, update, remove} from "@/api/anwise/stock/stock_summary";
  import {mapGetters} from "vuex";
  import { getToken } from '@/utils/auth';
  import { exportBlobPost } from '@/api/common';
  import { downloadXls } from '@/utils/util';
  import {selectStockHomeDict} from "@/api/anwise/stock_home";
  import NProgress from 'nprogress';
  import 'nprogress/nprogress.css';

  export default {
    data() {
      return {
        form: {},
        query: {},
          search:{},
        loading: true,
        page: {
          pageSize: 20,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        option: {
            height:'auto',
            calcHeight: 30,
            tip: false,
            searchShow: false,
            searchMenuSpan: 6,
            border: true,
            index: true,
            selection: true,
            reserveSelection:true,
            labelWidth: 150,
            searchLabelWidth:100,
            indexWidth:100,
            menuWidth: 210,
            addBtn: false,
            editBtn: false,
            viewBtn: false,
            delBtn: false,
            stripe: true,
            searchIndex: 3,
            searchIcon: false,
            searchEnter:true,
            menu: false,
            showSummary: true,
            // sumColumnList: [
            // //     // {
            // //     //     label: '合计:',
            // //     //     name: 'materialNo',
            // //     // },
            //     {
            //         label: '合计:',
            //         name: 'num',
            //         type: 'sum',
            //         decimals: 0
            //     },
            // ],
          column: [
            {
              label: "汇总仓存id",
              prop: "summaryId",
              type: "number",
                precision:0,
                min:0,
                controls:false,
                fixed: true,
                overHidden: true,
                sortable: true,
                width:150,
            },
            {
              label: "物料编号",
              prop: "materialNo",
              type: "input",
              search: true,
                fixed: true,
                overHidden: true,
                sortable: true,
                width:130,
              rules: [{
                required: true,
                message: "请输入物料编号",
                trigger: "blur"
              }],
            },
            {
              label: "客户条码",
              prop: "barCode",
              type: "input",
                search:true,
              overHidden: true,
              sortable: true,
              width:130,
            },
            {
              label: "物料名称",
              prop: "materialName",
              type: "input",
                search: true,
                overHidden: true,
                sortable: true,
                width:130,
            },
            {
              label: "规格",
              prop: "specification",
              type: "input",
              search:true,
              overHidden: true,
              sortable: true,
              width:130,
            },
              {
                  label: "物料类别",
                  prop: "type",
                  type: "select",
                  filterable:true,
                  search: true,
                  overHidden: true,
                  sortable: true,
                  multiple: true,
                  dicUrl: "/blade-system/dict-biz/dictionary?code=material_s_type",
                  width:120,
                  props: {
                      label: 'dictValue',
                      value: 'dictValue',
                  },
                  dataType: 'string',
                  rules: [{
                      required: true,
                      message: "请选择物料类别",
                      trigger: "blur"
                  }],
              },
              {
                  label: "所属机构",
                  prop: "deptName",
                  type: "input",
                  overHidden: true,
                  sortable: true,
                  hide:true,
                  width:130,
              },
            {
              label: "仓位",
              prop: "stockId",
              type: "select",
              filterable: true,
              span:8,
              dicData:[],
              props: {
                label: 'stockName',
                value: 'id',
              },
              // allowCreate:true,
              dataType: 'string',
              search: true,
              overHidden: true,
              sortable: true,
              width:120,
            },
            {
              label: "单位",
              prop: "unit",
              type: "input",
                overHidden: true,
                sortable: true,
                width:120,
            },
            {
              label: "数量",
              prop: "num",
              type: "input",
                sumColumn:true,
                overHidden: true,
                sortable: true,
                width:130,
            },
              {
                  label: "包装规格",
                  prop: "packSpec",
                  type: "input",
                  overHidden: true,
                  width:150,
              },
            {
              label: "包装箱数",
              prop: "packCtnNum",
              type: "input",
                overHidden: true,
                width:150,
            },
              {
                  label: "材质",
                  prop: "mcz",
                  type: "input",
                  overHidden: true,
                  sortable: true,
                  width:120,
              },
              {
                  label: "长度",
                  prop: "length",
                  type: "input",
                  value:0,
                  rules: [{
                      required: false,
                      message: "请输入长度",
                      trigger: "blur"
                  }],
                  overHidden: true,
                  sortable: true,
                  width:90,
              },
              {
                  label: "长度单位",
                  prop: "lengthUnit",
                  type: "input",
                  filterable:true,
                  // dicUrl: '/api/blade-anwise/unit_info/select?type=length',
                  // props: {
                  //     label: 'name',
                  //     value: 'name',
                  // },
                  // dataType: 'string',
                  value:'CM',
                  rules: [{
                      required: false,
                      message: "请选择长度单位",
                      trigger: "blur"
                  }],
                  overHidden: true,
                  sortable: true,
                  width:120,
              },
              {
                  label: "宽度",
                  prop: "width",
                  type: "input",
                  value:0,
                  rules: [{
                      required: false,
                      message: "请输入宽度",
                      trigger: "blur"
                  }],
                  overHidden: true,
                  sortable: true,
                  width:90,
              },
              {
                  label: "宽度单位",
                  prop: "widthUnit",
                  type: "input",
                  // filterable:true,
                  // dicUrl: '/api/blade-anwise/unit_info/select?type=length',
                  // props: {
                  //     label: 'name',
                  //     value: 'name',
                  // },
                  // dataType: 'string',
                  value:'CM',
                  rules: [{
                      required: false,
                      message: "请选择宽度单位",
                      trigger: "blur"
                  }],
                  overHidden: true,
                  sortable: true,
                  width:120,
              },
              {
                  label: "高度",
                  prop: "height",
                  type: "input",
                  value:0,
                  rules: [{
                      required: false,
                      message: "请输入高度",
                      trigger: "blur"
                  }],
                  overHidden: true,
                  sortable: true,
                  width:90,
              },
              {
                  label: "高度单位",
                  prop: "heightUnit",
                  type: "input",
                  // filterable:true,
                  // dicUrl: '/api/blade-anwise/unit_info/select?type=length',
                  // props: {
                  //     label: 'name',
                  //     value: 'name',
                  // },
                  // value:'CM',
                  // dataType: 'string',
                  rules: [{
                      required: false,
                      message: "请选择高度单位",
                      trigger: "blur"
                  }],
                  overHidden: true,
                  sortable: true,
                  width:120,
              },
              {
                  label: "系列代码",
                  prop: "seriesNo",
                  type: "select",
                  filterable:true,
                  dicUrl: '/api/blade-anwise/material_series/select',
                  props: {
                      label: 'seriesNo',
                      value: 'id',
                  },
                  dataType: 'string',
                  rules: [{
                      required: false,
                      message: "请选择系列代码",
                      trigger: "blur"
                  }],
                  overHidden: true,
                  sortable: true,
                  width:120,
              },
              // {
              //     label: "品牌代号",
              //     prop: "programCode",
              //     type:"select",
              //     filterable:true,
              //     dicUrl: '/api/blade-anwise/customer_group/select',
              //     props: {
              //         label: 'programCode',
              //         value: 'programCode',
              //     },
              //     dataType: 'string',
              //     rules: [{
              //         required: false,
              //         message: "请选择品牌代号",
              //         trigger: "blur"
              //     }],
              //     overHidden: true,
              //     sortable: true,
              //     width:120,
              // },
              {
                  label: "每外箱数量",
                  prop: "maxNum",
                  type: "input",
                  value:0,
                  rules: [{
                      required: false,
                      message: "请输入每外箱数量",
                      trigger: "blur"
                  }],
                  overHidden: true,
                  sortable: true,
                  width:130,

              },
              {
                  label: "每内箱数量",
                  prop: "minNum",
                  type: "input",
                  value:0,
                  rules: [{
                      required: false,
                      message: "请输入每外箱数量",
                      trigger: "blur"
                  }],
                  overHidden: true,
                  sortable: true,
                  width:130,

              },
              {
                  label: "每袋数量",
                  prop: "saveNum",
                  type: "input",
                  value:0,
                  rules: [{
                      required: false,
                      message: "请输入每外箱数量",
                      trigger: "blur"
                  }],
                  overHidden: true,
                  sortable: true,
                  width:120,
              },
            {
              label: "箱唛",
              prop: "packLabel",
              type: "input",
                overHidden: true,
                sortable: true,
                width:180,
            },
            {
              label: "箱唛颜色",
              prop: "labelColor",
              type: "input",
                overHidden: true,
                sortable: true,
                width:130,
            },
          ]
        },
        data: []
      };
    },
    computed: {
      ...mapGetters(["permission","userInfo"]),
      permissionList() {
        return {
          addBtn: this.validData(this.permission.stock_summary_add, false),
          viewBtn: this.validData(this.permission.stock_summary_view, false),
          delBtn: this.validData(this.permission.stock_summary_delete, false),
          editBtn: this.validData(this.permission.stock_summary_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
      mounted() {
        this.init();
          if (this.userInfo.role_name.includes('anwise_prod')) {
              let deptName = this.findObject(this.option.column, 'deptName');
              deptName.hide=false;
              deptName.search = true;
              deptName.searchValue="安伟塑料制品(深圳)有限公司";
              this.query.deptName = "安伟塑料制品(深圳)有限公司";
          } else {
              let deptName = this.findObject(this.option.column, 'deptName');
              deptName.hide=true;
              deptName.search = false;
          }
          this.onLoad(this.page);
      },
    methods: {
      init(){
        selectStockHomeDict().then(res=>{
          if(res.data.success){
            const stockId = this.findObject(this.option.column, 'stockId');
            stockId.dicData = res.data.data;
          }
        })
      },
        summaryMethod ({ columns, data }) {
            const sums = [];
            if (columns.length > 0) {
                sums[1] = '合计：';
                columns.forEach((column, index) => {
                    let prop = column.property
                    if (['num','packCtnNum'].includes(prop)) {
                        let values = this.data.map(item => Number(item[prop] || 0));
                        let all = values.length !== 0 ? sums[index] = values.reduce((a, b) => {
                            return a + b;
                        }) : 0
                        if (prop == 'num') {
                            sums[index] = this.$toFixed(all,0)
                        }
                        if(prop=='packCtnNum') {
                            sums[index] = this.$toFixed(all,0)
                        }
                        // else if (prop == 'avg') {
                        //     sums[index] = all / values.length || 0
                        // } else if (prop == 'count') {
                        //     sums[index] = values.length
                        // }
                    }
                });
            }
            return sums;
        },
        handleExport(){
            NProgress.start();
            exportBlobPost(
                `/blade-anwise/stock/stock_summary/export?${this.website.tokenHeader
                    }=${getToken()}`, this.query
            ).then(res => {
                downloadXls(res.data, `仓存汇总${this.$dayjs().format('YYYYMMDDHHmmss')}.xlsx`);
                NProgress.done();
            });
        },
      rowSave(row, done, loading) {
        add(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      rowUpdate(row, index, done, loading) {
        update(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      beforeOpen(done, type) {
        if (["edit", "view"].includes(type)) {
          getDetail(this.form.id).then(res => {
            this.form = res.data.data;
          });
        }
        done();
      },
        sortChange(val) {
            console.log(val)
            this.sort = {
                prop: val.prop,
                order: val.order
            };
            let order = "";
            if (this.sort.prop && this.sort.order) {
                if (this.sort.order === "descending") {
                    order = `${this.sort.prop} desc`
                } else {
                    order = `${this.sort.prop} asc`
                }
            }
            this.query.orderBy = order;
            this.onLoad(this.page);
        },
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
          this.onLoad(this.page, this.query);
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
          this.onLoad(this.page, this.query);
      },
      refreshChange() {
        this.onLoad(this.page, this.query);
      },
      onLoad(page, params = {}) {
        this.loading = true;
        params.selectType = 1;
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      }
    }
  };
</script>

<style>
</style>
